package com.yricky.poetcard.harmony;

import SimpleXml.Xml;
import SimpleXml.XmlNode;
import YUtils.B64;
import ohos.app.Context;

import java.io.*;
import java.util.Set;

public class SharedPreferences {

    private static SharedPreferences mInstance=null;
    private static XmlNode xmlNode;
    private static File file;
    private SharedPreferences(File _file){
        if(file==null)
            file=_file;
        xmlNode= Xml.parseXml(YUtils.FileUtils.readFile(file));
        if(xmlNode==null){
            xmlNode=XmlNode.EMPTY_NODE("configs");
        }
    }

    public static SharedPreferences getInstance(Context context){
        if(mInstance==null){
            File file=new File(context.getExternalFilesDir(null),"SP.xml");
            if (!file.exists()){
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            mInstance=new SharedPreferences(file);
        }
        return mInstance;
    }
    public String syncValue(String key,String value){
        if(key==null)
            return null;
        if(value!=null){
            xmlNode.removeAttr(key);
            xmlNode.setAttr(key, B64.s2b(value));
            save();
        }
        if(xmlNode.hasAttr(key))
            return B64.b2s(xmlNode.getAttr(key));
        return null;
    }
    public Set<String> getKeys(){
        return xmlNode.getAttrsName();
    }
    public void deleteValue(String key){
        xmlNode.removeAttr(key);
        save();
    }

    private void save(){
        try {
            Writer output=new FileWriter(file);
            Reader in = new CharArrayReader(xmlNode.toString().toCharArray());
            char[] buf = new char[1024];
            int bytesRead;
            while ((bytesRead = in.read(buf)) > 0)
                output.write(buf, 0, bytesRead);
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
